package com.ailk.tcm.hffw.android.common.model;

import java.io.File;

import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.HttpHandler;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ailk.tcm.R;
import com.ailk.tcm.hffw.android.common.MyApplication;
import com.ailk.tcm.hffw.android.common.entity.UpdateInfo;
import com.ailk.tcm.hffw.android.common.network.HttpUtil;
import com.alibaba.fastjson.JSON;

public class VersionModel {
	private static HttpUtil httpUtil = new HttpUtil();
	static{
		httpUtil.configTimeout(30000);
	}
	private static ProgressDialog pd;

	public static void checkUpdate(final Context context,
			final boolean background) {
		if (!background) {
			pd = new ProgressDialog(context);
			pd.setMessage("正在检查更新...");
			pd.show();
		}
		httpUtil.get(MyApplication.UPDATE_URL + "/update.json",
				new AjaxCallBack<String>() {
					@Override
					public void onSuccess(String t) {
						if (!background) {
							pd.dismiss();
						}
						UpdateInfo ui = JSON.parseObject(t, UpdateInfo.class);
						try {
							PackageInfo packageInfo = null;
							packageInfo = context
									.getPackageManager()
									.getPackageInfo(context.getPackageName(), 0);
							if (ui.getVersionCode() > packageInfo.versionCode) {
								showUpdateDialog(context, ui);
							} else {
								if (!background)
									Toast.makeText(context, "没有可用更新",
											Toast.LENGTH_SHORT).show();
							}
						} catch (Exception e) {
							if (!background)
								Toast.makeText(context, "检查更新出错",
										Toast.LENGTH_SHORT).show();
						}
					}

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						if (!background) {
							pd.dismiss();
						}
						if (!background)
							Toast.makeText(context, "检查更新出错",
									Toast.LENGTH_SHORT).show();
					}
				});
	}

	private static HttpHandler<?> downHandler;
	
	@SuppressLint("CutPasteId")
	private static void showUpdateDialog(final Context context,
			final UpdateInfo ui) {
		final Dialog d = new Dialog(context);
		d.requestWindowFeature(Window.FEATURE_NO_TITLE);
		d.setContentView(R.layout.dialog_update);
		final TextView titleView = (TextView) d.findViewById(R.id.title);
		titleView.setText("检查到新版本的"
				+ context.getResources().getString(R.string.app_name));
		TextView noteView = (TextView) d.findViewById(R.id.note);
		noteView.setText(ui.getNote());
		final View progressContainer = d.findViewById(R.id.progress_container);
		final ProgressBar pb = (ProgressBar) d.findViewById(R.id.progress);
		final View btnsContainer = d.findViewById(R.id.btn_container);
		Button cancelBtn = (Button) d.findViewById(R.id.cancel);
		Button okBtn = (Button) d.findViewById(R.id.ok);
		final Button cancelDownBtn = (Button) d.findViewById(R.id.cancel_down);
		d.setCancelable(!ui.isForceUpdate());
		if (ui.isForceUpdate()) {
			cancelBtn.setVisibility(View.GONE);
		}
		OnClickListener btnClickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.cancel:
					d.dismiss();
					break;

				case R.id.ok:
					d.setCancelable(false);
					btnsContainer.setVisibility(View.GONE);
					progressContainer.setVisibility(View.VISIBLE);
					cancelDownBtn.setVisibility(View.VISIBLE);
					titleView.setText("正在下载更新，请稍候...");
					final String target = MyApplication.DOWNLOAD_STORE_PATH + "weizu.apk";
					final String tempTarget = MyApplication.DOWNLOAD_STORE_PATH + "weizu.apk.temp";
					downHandler = httpUtil.download(MyApplication.UPDATE_URL
							+ "/" + ui.getPackageName(),
							tempTarget,
							true, new AjaxCallBack<File>() {

								@Override
								public void onLoading(long count, long current) {
									double progress = ((double) current)
											/ ((double) count);
									pb.setProgress((int) (progress * 100));
								}

								@Override
								public void onSuccess(File t) {
									File targetFile = new File(target);
									try{
										targetFile.delete();
										t.renameTo(targetFile);
										Intent intent = new Intent();
										intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
										intent.setAction(android.content.Intent.ACTION_VIEW);
										intent.setDataAndType(Uri.fromFile(targetFile),
												"application/vnd.android.package-archive");
										context.startActivity(intent);
									}catch (Exception e) {
										File tempTargetFile = new File(tempTarget);
										try {
											tempTargetFile.delete();
										} catch (Exception e1) {
										}
										Toast.makeText(context, "应用更新失败",
												Toast.LENGTH_SHORT).show();
									}
									d.dismiss();
								}

								@Override
								public void onFailure(Throwable t, int errorNo,
										String strMsg) {
									if(!"user stop download thread".equals(strMsg)){
										Toast.makeText(context, "下载更新包失败，请稍后重试",
												Toast.LENGTH_SHORT).show();
									}
									d.dismiss();
								}

							});
					break;
				case R.id.cancel_down:
					try {
						downHandler.stop();
					} catch (Exception e) {

					}
					break;
				}
			}
		};
		cancelBtn.setOnClickListener(btnClickListener);
		okBtn.setText("立即更新（" + ui.getPackageSize() + "M）");
		okBtn.setOnClickListener(btnClickListener);
		cancelDownBtn.setOnClickListener(btnClickListener);
		d.show();
	}
}
